import datetime
import json

from django_redis import get_redis_connection

from apps.homes.models import House
from apps.orders.models import Order
from apps.users.models import User
from utils.response_code import RET
from django import http
from django.views import View


# 订单
class OrdersView(View):
    def get(self, request):
        # 获取用户id,获取参数
        # user = request.user
        user = User.objects.get(id=1)

        role = request.GET.get('role')
        # 校验参数
        if not role:
            return http.JsonResponse({"errno": RET.PARAMERR, "errmsg": "参数错误"})

        # 判断下数据是否正确
        if role not in ['custom', 'landlord']:
            return http.JsonResponse({"errno": RET.PARAMERR, "errmsg": "参数错误"})
        # 判断是否是房客
        if role == 'custom':
            # 房客查看自己的下单
            order_msg = Order.objects.filter(user=user).order_by('-create_time')
        else:
            # 房东看自己的房子被下单
            house = House.objects.filter(user=user)
            house_ids = [house.id for house in house]
            order_msg = Order.objects.filter(house_id__in=house_ids).order_by('-create_time')

        # 构造数据
        # order_list=[order for order in order_msg]
        # 构造数据
        order_list = []
        for order in order_msg:
            order_list.append({
                "amount": order.house_price,
                "comment": order.comment,
                "ctime": order.create_time,
                "days": order.days,
                "end_date": order.end_date,
                "img_url": order.house.to_basic_dict()['img_url'],
                "order_id": order.id,
                "start_date": order.begin_date,
                "status": order.status,
                "title": order.house.title
            })
        # 响应结果
        return http.JsonResponse({
            "errno": RET.OK,
            "errmsg": "OK",
            "data": {"orders": order_list}
        })


# 添加订单
class OrdersAddView(View):
    def post(self, request):
        # 接收参数
        # user = request.user  # 用户,下面是测试用的
        user = User.objects.get(id=1)
        json_dict = json.loads(request.body.decode())
        house_id = json_dict.get('house_id')
        start_date = json_dict.get('start_date')
        end_date = json_dict.get('end_date')
        # 校验
        if not all([house_id, start_date, end_date]):
            return http.JsonResponse({"errno": RET.PARAMERR, "errmsg": "参数错误"})
        # 时间这个自己真不会写，但是能看懂
        start_date = datetime.datetime.strptime(start_date, "%Y-%m-%d")
        end_date = datetime.datetime.strptime(end_date, "%Y-%m-%d")
        # 判断下时间数据
        if end_date < start_date:
            return http.JsonResponse({"errno": RET.PARAMERR, "errmsg": "参数错误"})
        # 计算入住时间
        days = (end_date - start_date).days
        # 查寻数据库，是否有该房子存在
        try:
            house = House.objects.get(id=house_id)
        except Exception:
            return http.JsonResponse({"errno": RET.PARAMERR, "errmsg": "房屋号不存在"})
        # 判断是否是房东自己租自己的
        if user == house.user.id:
            return http.JsonResponse({"errno": RET.PARAMERR, "errmsg": "参数错误"})
        # 判断用户是否有空房可以租

        count = Order.objects.filter(house=house, end_date__gte=start_date, begin_date__lt=end_date).count()
        if count == 0:
            # 构造数据
            order = Order.objects.create(
                user=user,
                house=house,
                begin_date=start_date,
                end_date=end_date,
                days=days,
                house_price=house.price,
                amount=days * house.price
            )
            # 响应提交订单结果
            return http.JsonResponse({"errno": RET.OK, "errmsg": "下单成功", "order_id": order.id})
        else:
            return http.JsonResponse({"errno": RET.PARAMERR, "errmsg": "房屋已被占用"})


# 接单 拒单
class Orderstatus(View):
    def put(self, request, order_id):
        '''
        思路:接受参数,然后校验下存在不,然后通过参数中的str,分2种情况进行分别操作
        第一中是直接接单,然后返回响应
        第二种是拒单后,返回拒单原因并响应给前端
        '''
        # user = request.user
        user = User.objects.get(id=1)
        json_dict = json.loads(request.body.decode())
        action = json_dict.get("action")
        if action not in ['accept', 'reject']:
            return http.JsonResponse({"errno": RET.PARAMERR, "errmsg": "参数错误"})

        order = Order.objects.filter(id=order_id, status=Order.ORDER_STATUS["WAIT_ACCEPT"]).first()
        house = order.house
        # 这个未想到 ----判断订单是否存在并且当前房屋的用户id是当前用户的id----
        if not order or house.user != user:
            return http.JsonResponse({"errno": RET.NODATA, "errmsg": "数据有误"})

        # 接单
        if action == 'accept':
            # 修改状态
            order.status = Order.ORDER_STATUS["WAIT_COMMENT"]
            # 拒单
        elif action == 'reject':
            # 接收参数reason
            reason = json_dict.get('reason')
            if not reason:
                return http.JsonResponse({"errno": RET.PARAMERR, "errmsg": "没写原因"})
            else:
                # 写修改状态,并添加原因
                order.status = Order.ORDER_STATUS["REJECTED"]
                order.comment = reason
        # 保存状态,没打算try
        try:
            order.save()
        except Exception:
            return http.JsonResponse({"errno": RET.DBERR, "errmsg": "保存订单状态失败"})
        # 响应结果
        return http.JsonResponse({"errno": RET.OK, "errmsg": "操作成功"})


# 评价订单
class Ordercomment(View):
    def put(self, request, order_id):
        '''
        思路, 接受参数,查到对应的订单,进行写入保存即可,然后响应结果
        '''
        # 获取参数
        json_dict = json.loads(request.body.decode())
        comment = json_dict.get('comment')
        if not comment:
            return http.JsonResponse({"errno": RET.PARAMERR, "errmsg": "没写评价"})

        # 添加评论
        Order.objects.filter(id=order_id, status=Order.ORDER_STATUS["WAIT_COMMENT"]).update(
            comment=comment, status=Order.ORDER_STATUS["COMPLETE"])

        # 没想到订单数+1 和 删除redis缓存,事务有想到,没打算用
        order = Order.objects.get(id=order_id)
        house = order.house
        house.order_count += 1
        house.save()
        redis_con = get_redis_connection('house_cache')
        redis_con.delete('house_info_' + str(house.id))

        return http.JsonResponse({"errno": RET.OK, "errmsg": "评论成功"})
